package com.sdy.supermarket.task.order;

import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sdy.approval.api.ApprovalAllApi;
import com.sdy.common.model.BizException;
import com.sdy.mvc.annotation.TaskSync;
import com.sdy.supermarket.biz.mapper.GsAppIpMapper;
import com.sdy.supermarket.biz.mapper.GsOrderItemMapper;
import com.sdy.supermarket.biz.mapper.GsUserResMapper;
import com.sdy.supermarket.biz.model.GsAppIp;
import com.sdy.supermarket.biz.model.GsOrderItem;
import com.sdy.supermarket.biz.model.GsUserRes;
import com.sdy.supermarket.biz.service.GsAppIpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 定时查询数据库中待审批的订单并且发送给流程审批模块
 *
 * @author hyh
 */
@Component
@Slf4j
public class OrderItemTask {

    @Resource
    private GsOrderItemMapper itemMapper;
    @Autowired
    private ApprovalAllApi approvalAllApi;
    @Resource
    private GsUserResMapper userResMapper;
    @Resource
    private GsAppIpMapper gsAppIpMapper;

    @Scheduled(cron = "0/30 * * * * ?")
    @TaskSync
    public void sendOrderItemResIdList() throws BizException {
        List<Map<String, Object>> sendApprovalInfo = itemMapper.getSendApprovalInfo();
        if (sendApprovalInfo.size() != 0) {
            sendApprovalInfo.forEach(info -> info.put("res_id", "[政务超市]" + info.get("res_id")));
            // 未审批资源发送后需要改变状态为已发送
            log.info("调用方法");
            int i = approvalAllApi.lookResId(sendApprovalInfo);
            List<Integer> idList = sendApprovalInfo.stream().map(info -> (Integer) info.get("id")).collect(Collectors.toList());
            int update = itemMapper.update(new GsOrderItem().setState(3), Wrappers.<GsOrderItem>lambdaQuery().in(GsOrderItem::getId, idList));
            if (i == 0 || update == 0) {
                log.error("向流程审批模块发送数据失败");
                Assert.isTrue(true, "发送数据失败");
            } else {
                log.info("向流程审批模块发送数据成功");
            }
        } else {
            log.info("暂无需要提交到审批中心的数据");
        }
    }

    @Scheduled(cron = "0/30 * * * * ?")
    @TaskSync
    public void sendUserRes() {
        // 查询到已经申请成功的订单
        List<GsOrderItem> orderItemList = itemMapper.selectList(Wrappers.<GsOrderItem>lambdaQuery().eq(GsOrderItem::getState, 6).eq(GsOrderItem::getIsDone, 0).isNull(GsOrderItem::getVersionNo));
        List<GsUserRes> userResList = new ArrayList<>();
        orderItemList.forEach(order -> {
            userResList.add(new GsUserRes().setUserId(order.getUserId()).setResId(order.getResId()).setState(2).setCommonUse(0).setSrcDeptName("申请资源发放平台")
                    .setCreateTime(new Date()).setUpdateTime(new Date()).setDeptId(order.getDeptId()));
        });
        if (!userResList.isEmpty()) {
            List<Map<String, Object>> ipList = new ArrayList<>();
            StringBuilder ipIdList = new StringBuilder();
            // 设置状态为资源已发送
            orderItemList.forEach(item -> {
                item.setIsDone(1);
                Map<String, Object> map = new HashMap<>();
                ipIdList.append(item.getIpIdList());
                map.put("ipIdList", item.getIpIdList());
                map.put("resId", item.getResId());
                ipList.add(map);
            });
            List<GsAppIp> gsAppIps = gsAppIpMapper.selectList(Wrappers.<GsAppIp>lambdaQuery().in(GsAppIp::getId, Arrays.asList(new String(ipIdList).split(","))));
            List<GsAppIp> updateAppIpList = new ArrayList<>();
            for (GsAppIp appIp : gsAppIps) {
                for (Map<String, Object> map : ipList) {
                    String ipId = (String) map.get("ipIdList");
                    if (ipId.indexOf(appIp.getId() + "") != -1) {
                        updateAppIpList.add(new GsAppIp().setId(appIp.getId()).setResIdList(appIp.getResIdList() + "," + map.get("resId")));
                        ((String) map.get("ipIdList")).replace(appIp.getId() + "", "");
                    }
                }
            }
            int appIpUpdate = gsAppIpMapper.batchUpdate(updateAppIpList);
            int batchUpdate = itemMapper.batchUpdate(orderItemList);
            int batchInsert = userResMapper.batchInsert(userResList);
            log.info(batchInsert != 1 || batchUpdate != 1 || appIpUpdate != 1 ? "向用户发放所申请的资源成功" : "向用户发放所申请的资源失败");
        } else {
            log.info("没有需要发放的资源");
        }
    }

}
